using UnityEngine;
using System.Collections;

public class bounds_checker : MonoBehaviour {
	// TODO: something less crappy
	private const float RADIUS = 50;
	private const float WAIT_TIME = 5;
	private const int MAX_STATIONARY_EPOCHS = 2;
	Vector3 last_position;
	bool last_position_init;
	float last_time;
	private int stationary_epochs;
	
	// Use this for initialization
	void Start () {
		this.last_position = new Vector3(0,0,0);
		this.last_position_init = false;
		this.last_time = 0;
		this.stationary_epochs = 0;
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	void FixedUpdate () {
		bool stationary;
		if (!this.last_position_init) {
			this.last_position = this.transform.position;
			this.last_position_init = true;
		}
		
		if ((this.last_time > 0) && (Time.fixedTime - this.last_time < bounds_checker.WAIT_TIME)) {
			/* only check every few seconds */
			return;
		} else {
			this.last_time = Time.fixedTime;
		}
		
		stationary = (this.last_position == this.transform.position);
		this.last_position = this.transform.position;
		if (stationary) {
			/* This is assuming the bounds check is expensive, which it doesn't seem to be */
			this.stationary_epochs++;
			if (this.stationary_epochs >= bounds_checker.MAX_STATIONARY_EPOCHS) {
				Debug.Log ("destroyed (stuck)!");
				this.DestroySelf();
			}
			return;
		}
		
		this.stationary_epochs = 0;
		
		if (this.transform.position.magnitude > bounds_checker.RADIUS) {
			Debug.Log ("destroyed (out-of-bounds)!");
			this.DestroySelf();
		}
	}
	
	private void DestroySelf() {
		Destroy (this.gameObject);
	}
}
